package com.wang.transfer.util.algorithm;

import java.util.Arrays;

/**
 * 最长公共前缀
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] strs = new String[]{"flower","flow","flight"};
        String prefix = new LongestCommonPrefix().longestPrefix(strs);
        System.out.println(prefix);
    }

    public String longestPrefix(String[] strs) {
        StringBuilder s = new StringBuilder();

        final int[] len = {1000};
        Arrays.stream(strs).forEach((a) -> {
            len[0] = Math.min(len[0], a.length());
        });
        for (int i = 0; i < len[0]; i++) {
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (c != strs[j].charAt(i)) {
                    return s.toString();
                }
            }
            s.append(c);
        }
        return s.toString();
    }
}
